package org.nf.web.mapping;

import jakarta.servlet.http.HttpServletRequest;
import org.nf.web.annotation.RequestMapping;
import org.nf.web.config.Configure;
import org.nf.web.servlet.HandlerMapping;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author lzp
 * @Date 2024-05-15
 * 根据方法来擦查找
 */
public class MethodHanlerMapping implements HandlerMapping {

    /**
     * 用于存放匹配的映射方法
     * key是请求的uri,value是对应的方法对象
     */
    private Map<String,Method> map = new HashMap<>();

    @Override
    public void init(Configure configure) {
        Set<Class<?>> classes = configure.getClasses();
        classes.forEach( clazz -> {
            String prefix ="";
            //类上声明了注解则作为请求url的前缀
            if (clazz.isAnnotationPresent(RequestMapping.class)){
                prefix = clazz.getAnnotation(RequestMapping.class).value();
            }
            //遍历类里面的所有方法,找出带有注解的Method
            for (Method method : clazz.getMethods()){
                if (method.isAnnotationPresent(RequestMapping.class)){
                    //构件完整的请求地址
                    String uri = prefix + method.getAnnotation(RequestMapping.class).value();
                    //将uri和method保存搭配map集合中
                    map.put(uri,method);
                }
            }
        });
    }

    @Override
    public Object getHandler(HttpServletRequest request) {
        String uri = request.getRequestURI();
        //去掉contextPath前缀
        uri = uri.replace(request.getContextPath(),"");
        //根据请求的uri找到匹配的method对象返回
        return map.get(uri);
    }
}
